/**
 * 数组工具类
 */
const SPLIT_REG_EXP = /[,，]/

// 字符串 转 数组
export function strToArr(str: string) {
	let list: string[] = []
	if (str) {
		list = str.split(SPLIT_REG_EXP)
	}
	return list
}

// 数组 转 字符串
export function arrToStr(list: []) {
	let str = ''
	if (list) {
		str = list.join(',')
	}
	return str
}

// 根据数组元素 id 获取元素 name
export function getNameById(list: any[], id: any, nameField = 'name', idField = 'id') {
	let name = ''
	if (list) {
		const item = list.find((item: { [x: string]: any }) => item[idField] === id)
		if (item && item[nameField]) {
			name = item[nameField]
		}
	}
	return name
}

export function getTextTById(list: any[], id: any) {
	return getNameById(list, id, 'textT')
}

export function getTextById(list: any[], id: any) {
	return getNameById(list, id, 'text')
}

// 获取数组最大最小值
export function arrMinMax(arr: any[], valueField = 'value') {
	let min: number | undefined, max: number | undefined
	arr.forEach((item: { [x: string]: any }) => {
		const value = item[valueField]
		if (min === undefined || value < min) {
			min = value
		}
		if (max === undefined || value > max) {
			max = value
		}
	})
	return [min, max]
}

export function getItemById<T>(arr: any, id: any, idField = 'id') {
	if (!arr) {
		return null
	}
	for (const item of arr) {
		if (item[idField] === id) {
			return item as T
		}
	}
	return null
}

// 遍历树形数组
export function getTreeNodeById(arr: [], id: string | number, idField = 'id') {
	let res: any = null
	arr.forEach((item) => {
		if (res) {
			return res
		}
		if (item[idField] === id) {
			res = item
		} else if (item['children']) {
			res = getTreeNodeById(item['children'], id, idField)
		}
	})
	return res
}

export function removeByItem(arr: any[], item: any) {
	if (arr && item) {
		const index = arr.indexOf(item)
		if (index !== -1) {
			arr.splice(index, 1)
		}
	}
}

export function uniqueFunc(arr: [], uniId: string | number) {
	const res = new Map()
	return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1))
}

export function union(a: any[], b: any[]) {
	return Array.from(new Set([...a, ...b]))
}

export function intersect(a: any[], b: any[]) {
	return a.filter((x) => b.includes(x))
}

export function difference(a: any[], b: any[]) {
	return a.filter((x) => !b.includes(x))
}

export function removeById(arr: any[], id: string | number, idField = 'id') {
	let res
	let index = -1
	for (let i = 0; i < arr.length; i++) {
		const item = arr[i]
		if (item[idField] === id) {
			index = i
			break
		}
	}
	if (index > -1) {
		res = arr[index]
		arr.splice(index, 1)
	}
	return res
}

export function getIndexById(arr: any[], id: string | number, idField = 'id') {
	for (let i = 0; i < arr.length; i++) {
		const item = arr[i]
		if (item[idField] === id) {
			return i
		}
	}
	return -1
}
